using System.Text.Json;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace SerializerDemo;

[ObservableObject]
public partial class MainPageViewModel {
    [ObservableProperty] private string _result;

    [RelayCommand]
    private void Serialize() {
        var clazz = new Clazz {
            Id = 1,
            Name = "Class 1",
            Students = new List<Student> {
                new() { Id = 1, Name = "Student 1" },
                new() { Id = 1, Name = "Student 2" }
            }
        };

        Result = JsonSerializer.Serialize(clazz);
    }

    [RelayCommand]
    private void SerializeWithOptions() {
        var clazz = new Clazz {
            Id = 1,
            Name = "Class 1",
            Students = new Student[] {
                new() { Id = 1, Name = "Student 1" },
                new() { Id = 1, Name = "Student 2" }
            }
        };

        Result = JsonSerializer.Serialize(clazz,
            new JsonSerializerOptions { WriteIndented = true });
    }

    [RelayCommand]
    private void Deserialize() {
        var clazz = JsonSerializer.Deserialize<Clazz>(JsonString);

        Result = clazz.Students.GetType().ToString();
    }

    [RelayCommand]
    private void DeserializeWithOptions() {
        var clazz = JsonSerializer.Deserialize<Clazz>(JsonString.ToLower(),
            new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

        Result = clazz.Students.GetType().ToString();
    }

    private const string JsonString =
        "{\"Id\":1,\"Name\":\"Class 1\",\"Students\":[{\"Id\":1,\"Name\":\"Student 1\"},{\"Id\":1,\"Name\":\"Student 2\"}]}";
}

public class Clazz {
    public int Id { get; set; }

    public string Name { get; set; }

    public IEnumerable<Student> Students { get; set; }
}

public class Student {
    public int Id { get; set; }

    public string Name { get; set; }
}